﻿using System;
using System.Collections.Generic;
using System.Linq;

using SharedGenomics.Core;
using SharedGenomics.Workbench.Core;
using SharedGenomics.Domain;
using SharedGenomics.DataTransfer;
using SharedGenomics.Workbench.Services;

namespace SharedGenomics.Workbench.Models
{
    public class RemoteJobDetailsRepository : WCFClientHost, IJobDetailsRepository
    {
        private IDictionary<int, JobDetails> _cachedJobs;

        public RemoteJobDetailsRepository(IDataService service)
        {
            this.Service = service;
            this._cachedJobs = new Dictionary<int, JobDetails>();
        }

        public Maybe<IEnumerable<JobDetails>> GetUserJobs(JobSpecification specification)
        {
            //construct the list of job ids not to be returned by the service - an id should be ignored if:
            // - it is in the cache AND
            // - the job has completed
            var completedJobIds = this._cachedJobs.Where(kvp => kvp.Value.Status.IsComplete()).Select(kvp => kvp.Key).ToArray();

            //get outstanding jobs from service that meet the spec and add to cache
            return this.Service.GetUserJobs(specification, completedJobIds).Bind(jobs =>
            {
                //add new jobs to cache
                foreach (JobDetails jd in jobs)
                {
                    this._cachedJobs[jd.Id] = jd;
                }

                //get all user jobs that match the specification (the ones in the cache and the new ones returned by the service)
                return this._cachedJobs.Values.Where(jd => specification.Matches(jd)).ToArray().AsEnumerable();
            });
        }

        private IDataService Service { get; set; }
    }
}
